const bar = document.querySelector('.leftbar')
let num1 = ''
let list1 = []
let rankDataCache = null;
let sum1 = '全部榜单'
let sum2
let sum3
axios.get('https://app2.motie.com/ranking/names', {
  // 1. 添加必要的请求头（关键：os 和 sd 必须传）
  headers: {
    'os': 'pc', // 设备类型：pc（从正常请求中复制）
  },
}).then(res => {
  let u = ''
  res.data.data.forEach((item, index) => {
    num1 = item.value
    u += `
        <li onclick='rankBar(event,${index},${num1})'>${item.desc}</li>
    `
  })
  bar.innerHTML = `
    <ul>      
        <li class="allbar" onclick='rankBar(event)'>全部榜单</li>
        ${u}
    </ul>
  `
}).catch(err => {
  console.log('请求错误详情：', err);
});
const x1 = 0
const rankBar = (e, x, num1) => {
  sum3 = num1
  sum2 = x
  sum1 = e.target.innerHTML
  console.log(list1)
  const li = document.querySelectorAll('.leftbar ul li')
  if (li.length === 0) return;
  li.forEach((item1, index1) => {
    if (!item1) return;
    item1.classList.remove('on')
    if (index1 == 0) {
      item1.classList.remove('allbar')
      color = '';
    }
  })
  if (e.target) {
    e.target.classList.add('on');
  }
  const rightMain = document.querySelector('.rightMain')
  const rightTwo = document.querySelector('.rightTwo')
  if (e.target.innerHTML == '全部榜单') {
    rightTwo.style.display = 'none'
    rightMain.style.display = 'block'
  } else {
    rightMain.style.display = 'none'
    rightTwo.style.display = 'block'
    axios.get(`https://app2.motie.com/ranking/detail?group=${list1[x].length}&siteId=1&rankType=${num1}&pageSize=30`).then(res => {
      rightTwo.innerHTML = ''
      let two = ''
      res.data.data.forEach((item5, index5) => {
        const date = new Date(item5.lastChapterTime);
        const year = date.getFullYear();
        const month = date.getMonth() + 1; // 月份从0开始，需+1
        const day = date.getDate();
        const hours = date.getHours();
        const minutes = date.getMinutes();
        const seconds = date.getSeconds();
        // 补零函数：小于10的数字前加0
        const padZero = (num) => num < 10 ? '0' + num : num;
        // 格式化时间
        const newDate = `${year}-${padZero(month)}-${padZero(day)} ${padZero(hours)}:${padZero(minutes)}:${padZero(seconds)}`;
        two += `
        <div class="secd">
            <div class="secdLeft">
                <a onclick="jumps(${item5.bookId}); event.preventDefault();" class="pic" href="javascript:;"><img src="${item5.bookIconUrl}" alt=""></a>
                
                <div class="leftCon">
                    <a onclick="jumps(${item5.bookId}); event.preventDefault();" class="bookName"><span class="bookNum">${index5 + 1}</span>重生1961：我从打猎开始发家致富</a>
                    <p class="leftNa">
                        <a href="">${item5.authorName} </a>|
                        <a href="">${item5.categoryVO.name} </a>| ${item5.finished == false ? '连载' : '完结'}
                        <span>1082531 总字数</span>
                    </p>
                    <p class="info">
                        ${item5.introduce}</p>
                    <p class="leftNa">
                        <a href="" class="red">最近更新
                            ${item5.lastChapterName}</a>
                        <span class="naTime">| ${newDate}</span>
                    </p>
                </div>
            </div>
            <div class="bigBtn">
                <a href="" class="detailBtn">书籍详情</a>
                <a href="" class="addBtn">加入书架</a>
            </div>
        </div>
      `
      })
      let tim = ''
      list1[x].forEach((time1, indext) => {
        tim += `
          <p onclick='jumpTime(event,${indext + 2})' class='getTime'>${time1} 榜</p>
        `
      })
      rightTwo.innerHTML = `
      <div class="menu">
          <span>${e.target.innerHTML}</span>
          <div class="fl">
            ${tim}
          </div>
      </div>
      <div class="fault">
          ${two}
      </div>
    `
      const fl = document.querySelectorAll('.getTime')
      fl.forEach((fls, ind) => {
        if (ind == 0) {
          fls.classList.add('active')
        }
      })
      const bookNum = document.querySelectorAll('.bookNum')
      bookNum.forEach((bo, indexBo) => {
        if (indexBo < 3) {
          console.log(333)
          bo.classList.add('fronts')
        }
      })
    }).catch(err => {
      console.log(err)
    })

  }

}
function render(x) {
  const request = rankDataCache
    ? Promise.resolve(rankDataCache)  // 直接用缓存
    : axios.get('https://app2.motie.com/ranking/all?siteId=1', {  // 第一次才请求
      headers: { 'os': 'pc', 'sd': 'pc-web-1.0', },
    }).then(res => {
      // 3. 缓存数据
      rankDataCache = res.data.data.sort((a, b) => a.type - b.type);
      return rankDataCache;
    });
  request.then(res => {
    const rightMain = document.querySelector('.rightMain')
    rightMain.innerHTML = '';
    list1 = []
    res.forEach((item2, sub1) => {
      let it = ''
      let it1 = ''
      const list2 = []
      item2.item.forEach((sum, sub) => {
        if (sum.title != '其他') {
          list2.push(sum.title)
        }
        it1 += `
        ${sum.title != '其他' ? `<li onmouseover="changeTime(event,'${sub}','${sub1}')">${sum.title}</li>` : ''}
      `
      })
      list1.push(list2)
      item2.item[x].content.forEach((item3, index3) => {
        it += `
        <ul>
          <li class="top">
              <p class="numOne fir">${index3 + 1}</p>
              <div class="bookBlock">
                  ${index3 == 0 ? `<img onclick="jumps(${item3.bookId}); return false;"  src="${item3.bookIconUrl}" alt="">` : ''}
                  ${index3 == 0 ? `<div class="boRight">
                      <a onclick="jumps(${item3.bookId}); return false;"  href="">${item3.bookName}</a>
                      <p class="name1">作者：<a href="">${item3.authorName}</a></p>
                  </div>`: `<a onclick="jumps(${item3.bookId}); return false;"  href="" class="titleName">${item3.bookName}</a>`}
              </div>
          </li>
        </ul>
      `
      })
      const currentRankHtml = `
        <div class="allRank current-rank">
          <div class="listTab">
              <div class="listTitle">
                  <h2>${item2.name}</h2>
              </div>
              <ul class="tabUl">
                  ${it1}
              </ul>
              <div class="rankBox">
                  ${it}
              </div>
            </div>
        </div>
     `
      rightMain.innerHTML += currentRankHtml
      const currentNumOne = document.querySelectorAll('.current-rank .numOne');
      currentNumOne.forEach((item4, index4) => {
        if (index4 < 3) { // 只给当前榜单的前3个加类
          item4.classList.add('front');
        }
      });
      // 移除临时类（避免影响后续操作）
      document.querySelector('.current-rank').classList.remove('current-rank');
    })
  }).catch(err => {
    console.log('请求错误详情：', err);
  });
}
render(0)
const changeTime = (event, sub, sub1) => {
  if (!rankDataCache) {
    // 缓存未加载时，先执行一次render获取数据（仅会请求一次）
    render(0).then(() => changeTime(event, sub, sub1));
    return;
  }
  const res = rankDataCache;
  const allRank = document.querySelectorAll('.allRank')
  if (allRank.length === 0) {
    return;
  }
  allRank.forEach((a, i) => {
    if (!a) return;
    if (i == sub1) {
      a.innerHTML = ''
      let it = ''
      let it1 = ''
      res[sub1].item.forEach((sum, sub) => {
        it1 += `
            ${sum.title != '其他' ? `<li class="lineColor" onmouseover="changeTime(event,'${sub}','${sub1}')">${sum.title}</li>` : ''}
          `
      })
      res[sub1].item[sub].content.forEach((item3, index3) => {
        it += `
          <ul>
            <li class="top">
                <p class="numOne fir">${index3 + 1}</p>
                <div class="bookBlock">
                    ${index3 == 0 ? `<img src="${item3.bookIconUrl}" alt="">` : ''}
                    ${index3 == 0 ? `<div class="boRight">
                        <a href="">${item3.bookName}</a>
                        <p class="name1">作者：<a href="">${item3.authorName}</a></p>
                    </div>`: `<a href="" class="titleName">${item3.bookName}</a>`}
                </div>
            </li>
          </ul>
        `
      })
      a.innerHTML = `
            <div class="listTab">
                <div class="listTitle">
                    <h2>${res[sub1].name}</h2>
                </div>
                <ul class="tabUl">
                    ${it1}
                </ul>
                <div class="rankBox">
                    ${it}
                </div>
            </div>
        `
      const currentRank = document.querySelectorAll('.allRank')[sub1];
      if (!currentRank) return; // 确保当前榜单存在
      const lineColor = currentRank.querySelectorAll('.tabUl li'); // 仅当前榜单内的标签
      lineColor.forEach((el, idx) => {
        if (idx == sub) {
          el.style.color = '#ff4d4f'; // 选中的标签变红
          el.style.borderBottom = '2px solid #ff4d4f';
          el.style.paddingBottom = '2px'
        } else {
          el.style.color = ''; // 未选中的恢复默认
          el.style.borderBottom = 'none';
          el.style.paddingBottom = ''
        }
      })
      const currentNumOne = a.querySelectorAll('.numOne');
      currentNumOne.forEach((item4, index4) => {
        if (index4 < 3) { // 只给当前榜单的前3个加类
          item4.classList.add('front');
        }
      });
    }
  })
}
function jumpTime(e, indext) {
  const currentTimeText = e.target.innerHTML
  const timeElements = document.querySelectorAll('.getTime');
  timeElements.forEach(el => {
    el.classList.remove('active');
  });
  e.target.classList.add('active');
  const rightTwo = document.querySelector('.rightTwo')
  axios.get(`https://app2.motie.com/ranking/detail?group=${indext}&siteId=1&rankType=${sum3}&pageSize=30`).then(res => {
    rightTwo.innerHTML = ''
    let two = ''
    res.data.data.forEach((item5, index5) => {
      const date = new Date(item5.lastChapterTime);
      const year = date.getFullYear();
      const month = date.getMonth() + 1; // 月份从0开始，需+1
      const day = date.getDate();
      const hours = date.getHours();
      const minutes = date.getMinutes();
      const seconds = date.getSeconds();
      // 补零函数：小于10的数字前加0
      const padZero = (num) => num < 10 ? '0' + num : num;
      // 格式化时间
      const newDate = `${year}-${padZero(month)}-${padZero(day)} ${padZero(hours)}:${padZero(minutes)}:${padZero(seconds)}`;
      two += `
        <div class="secd">
            <div class="secdLeft">
                <a onclick="jumps(${item5.bookId}); event.preventDefault();" class="pic" href="javascript:;"><img src="${item5.bookIconUrl}" alt=""></a>
                
                <div class="leftCon">
                    <a onclick="jumps(${item5.bookId}); return false;"  href="" class="bookName"><span>${index5 + 1}</span>重生1961：我从打猎开始发家致富</a>
                    <p class="leftNa">
                        <a href="">${item5.authorName} </a>|
                        <a href="">${item5.categoryVO.name} </a>| ${item5.finished == false ? '连载' : '完结'}
                        <span>1082531 总字数</span>
                    </p>
                    <p class="info">
                        ${item5.introduce}</p>
                    <p class="leftNa">
                        <a href="" class="red">最近更新
                            ${item5.lastChapterName}</a>
                        <span class="naTime">| ${newDate}</span>
                    </p>
                </div>
            </div>
            <div class="bigBtn">
                <a href="" class="detailBtn">书籍详情</a>
                <a href="" class="addBtn">加入书架</a>
            </div>
        </div>
      `
    })
    let tim = ''
    if (list1[sum2].length != 0) {
      list1[sum2].forEach((time1, indext) => {
        tim += `
            <p onclick='jumpTime(event,${indext + 1})' class='getTime'>${time1} 榜</p>
          `
      })
    }
    rightTwo.innerHTML = `
      <div class="menu">
          <span>${sum1}</span>
          <div class="fl">
            ${tim}
          </div>
      </div>
      <div class="fault">
          ${two}
      </div>
    `
    const bookName = document.querySelectorAll('.bookName span')
    bookName.forEach((book, boo) => {
      if (boo < 3) {
        book.classList.add('fronts')
      }
    })
    const ge = document.querySelectorAll('.getTime')
    ge.forEach(g => {
      // 比较新元素的文本与之前记录的“当前点击文本”
      if (g.innerHTML == currentTimeText) {
        g.classList.add('active');
      }
    });
  }).catch(err => {
    console.log(err)
  })
}
function jumps(id){
    if(localStorage.getItem('account')){
        window.location.href=`./laikan-bookDetail.html?id=${id}`
    }else{
        window.location.href='./login.html'
    }
    
}



